package base

import (
	"github.com/ruoklive/proxypool/pkg/log"
	"github.com/ruoklive/proxypool/pkg/models"
	"go.uber.org/zap"
	"io"
	"net/http"
	"regexp"
	"strconv"
)

var hc http.Client
func init(){
	// 限制连接数
	transport := &http.Transport{
		MaxIdleConns:        100,
		MaxIdleConnsPerHost: 100,
	}
	hc = http.Client{
		Transport:transport,
	}
}

type ParseFnc func(body io.ReadCloser) []*models.IP

type Base struct {
	requestUrl string
	parseFnc   ParseFnc
	log.Log
}

func NewBase(requestUrl string, parseFnc ParseFnc, logPrefix string) Base {
	return Base{requestUrl: requestUrl, parseFnc: parseFnc, Log: log.NewTLog(logPrefix)}
}

func (d Base) Execute() []*models.IP {
	r,_ := http.NewRequest("GET",d.requestUrl,nil);
	r.Header.Set("User-Agent","Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Mobile Safari/537.36")


	//resp, err := http.Get(d.requestUrl)
	resp,err := hc.Do(r)
	if err != nil {
		d.Error("Request fail ！", zap.Error(err))
		return nil
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		d.Error("Request status error ！", zap.Int("status", resp.StatusCode))
		return nil
	}
	ips := d.parseFnc(resp.Body)

	return ips
}

func (d Base) ExtractSpeed(oritext string) int64 {
	reg := regexp.MustCompile(`\d+?\.?\d*`)
	temp := reg.FindStringSubmatch(oritext)

	if len(temp) >= 1 && temp[0] != "" {
		speedFloat, _ := strconv.ParseFloat(temp[0], 64)
		speed := int64(speedFloat * 1000)
		return speed
	}
	return -1
}

// IP Regexp
func (d Base) IPRegexp() *regexp.Regexp  {
	return regexp.MustCompile(`((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\:([0-9]+)`)
}
